import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: const Text("我的第一个Flutter组件"),
          ),
          body: const DioDemo() // 列表,
          )));
}

class DioDemo extends StatefulWidget {
  const DioDemo({Key? key}) : super(key: key);

  @override
  _DioDemoState createState() => _DioDemoState();
}

class _DioDemoState extends State<DioDemo> {
  List _data = [];

  @override
  void initState() {
    // 使用initState来初始化数据 必须执行super.initState()
    getData();
    super.initState();
  }

  getData() async {
    // 在括号后面加上async
    // 异步请求数据
    String BASE_URL = "https://geek.itheima.net"; // 请求基础地址

    Dio dio = Dio();

    var res = await dio.get('$BASE_URL/v1_0/channels');

    setState(() {
      _data = res.data["data"]["channels"] as List;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GridView(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4, mainAxisExtent: 10, mainAxisSpacing: 10),
      children: _data.map((item) {
        // 遍历数据
        return Container(
          color: Colors.red,
          margin: const EdgeInsets.all(10),
          child: Text(
            item["name"],
            style: const TextStyle(color: Colors.white, fontSize: 20),
          ),
        );
      }).toList(), // 必须要加上toList() 否则会报错
    );
  }
}
